import 'package:flutter/material.dart';
import 'package:flutter_rider/event/click_address_event.dart';
import 'package:flutter_rider/event/click_operators_event.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/main/models/operator_model.dart';

import '../../../api/api.dart';
import '../../../event/click_carplate_event.dart';
import '../../../module/task/provider/task_operator_provider.dart';
import '../../models/carplate_model.dart';
import '../dialog/alert_dialog.dart';

class PopCarPlaterUserList extends  ConsumerStatefulWidget {

  String station;
  PopCarPlaterUserList( this.station,{Key? key}) : super(key: key);

  @override
  ConsumerState createState() => _PopCarPlateUserListState();
}

class _PopCarPlateUserListState extends  ConsumerState<PopCarPlaterUserList> {
  final _inputController = TextEditingController(text: "");
  List<CarPlateModel> _data = [];
  List<CarPlateModel> _result = [];

  @override
  void initState() {
    super.initState();

  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      padding: EdgeInsets.only(left: MediaQuery.of(context).padding.left, right: MediaQuery.of(context).padding.right),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(8.rpx)),
      ),
      child: Column(
        children: [
          8.hspace,
          _renderTitle(),
          4.hspace,
          _renderInput(),
          16.hspace,
          Expanded(
            child: StateLayout(
              dataCallback: _onDataCallback,
              url: "/user/truck_list?page_size=1000",
              childBuilder: _renderContent,
            ),
          ),
        ],
      ),
    );
  }

  Widget _renderTitle() {
    return Container(
        height: 70.rpx,
        alignment: Alignment.center,
        child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              40.wspace,
              Expanded(
                  child: Container(
                    alignment: Alignment.center,
                    child: UText.get("车辆选择", Colors.black, 20.rpx,fw: FontWeight.bold),
                  )),
              InkWell(
                child: SvgPicture.asset(R.image_close, width: 24.rpx, height: 24.rpx),
                onTap:  () {
                  Navigator.of(context).pop();
                },
              ),
              16.wspace,
            ])
    );
  }

  Widget _renderInput() {
    return Container(
        color: UIColor.color_content,
        padding: EdgeInsets.only(
          left: 16.rpx,
        ),
        child:Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Expanded(
                child: TextField(
                  onChanged: _onTextChange,
                  controller: _inputController,
                  textInputAction: TextInputAction.done,
                  maxLength: 20,
                  decoration: InputDecoration(
                    constraints: BoxConstraints(minHeight: 44.rpx, maxHeight: 44.rpx),
                    counterText: "",
                    contentPadding: EdgeInsets.symmetric(vertical: 12.rpx, horizontal: 12.rpx),
                    isCollapsed: true,
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(
                          4.rpx,
                        ),
                        borderSide: BorderSide.none
                    ),
                    prefixIcon: Padding(
                      padding: EdgeInsets.only(left: 12.rpx, right: 4.rpx),
                      child: Icon(
                        Icons.search,
                        size: 20.rpx,
                        color: Colors.black.withOpacity(0.4),
                      ),
                    ),
                    prefixIconConstraints: BoxConstraints(maxHeight: 16.rpx),
                    hintText: "请输入车牌号搜索",
                    hintStyle: TextStyle(color: const Color(0x66000000).withOpacity(0.4)),
                    filled: true,
                    fillColor: UIColor.color_input,
                    suffixIconConstraints: BoxConstraints(maxHeight: 16.rpx),
                    suffixIcon: _inputController.text.isNotEmpty? Container(
                      padding: EdgeInsets.only(right: 13.rpx),
                      child: GestureDetector(
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(150),
                            color: UIColor.color_t7,
                          ),
                          child: Icon(
                            Icons.close,
                            color: UIColor.color_content,
                            size: 16.rpx,
                          ),
                        ),
                        onTap: () {
                          _inputController.text = "";
                          _onTextChange("");
                        },
                      ),
                    ) : null,
                  ),
                ),
              ),
              16.wspace,
              _inputController.text.isNotEmpty?GestureDetector(
                  onTap: () {
                    _inputController.text = "";
                    _onTextChange("");
                  },
                  child: Row(
                    children: [
                      UText.get("取消", UIColor.color_primary, 16.rpx),
                      16.wspace
                    ],
                  )
              ):0.wspace,

            ]
        )
    );
  }

  _onDataCallback(dynamic data) {
    List list = [];
    for (var element in data) {
      list.add(element);
    }
    for (var element in list) {
      _data.add(CarPlateModel.fromMap(element));
      _result.add(CarPlateModel.fromMap(element));
    }
    // List list = [];
    // list.insert(0,{"id":"","name":"","mobile":"","isCheck":true,"isDefault":true,"title1":'',"title2":'',"title3":'',"title4":'',"title5":'',"title6":''});
    // for (var element in data) {
    //   list.add({...element,"isCheck": false,"isDefault":false,"title1":'',"title2":'',"title3":'',"title4":'',"title5":'',"title6":''});
    // }
    // for (var element in data) {
    //   list.add(element);
    // }
    // for (var element in list) {
    //   _data.add(OperatorModel.fromMap(element));
    //   _result.add(OperatorModel.fromMap(element));
    // }
  }

  Widget _renderContent(dynamic data) {
    if (_result.isEmpty) {
      return Center(
        child: UText.getSubText("暂无数据内容"),
      );
    }
    return ListView.separated(
      itemBuilder: _renderItem,
      itemCount: _result.length,
      separatorBuilder: _renderSeparator,
    );
  }

  Widget _renderSeparator(BuildContext context, int index) {
    return Container(
      margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
      height: 0.5.rpx,
      color: const Color(0xffE7E7E7),
    );
  }

  Widget _renderItem(BuildContext context, int index) {
    var item = _result[index];
    String time = item.time.substring(0,16);
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 16.rpx,horizontal: 16.rpx),
        child:Row(
          children: [
            Container(
              width: 80.rpx,
              child: UText.get(item.plateNo, UIColor.color_primary, 14.rpx),
            ),
          LimitedBox(
            maxWidth: 150.rpx,
            child: Text(item.parkName, style: TextStyle(color:UIColor.color_t7,fontSize: 14.rpx),overflow: TextOverflow.ellipsis,maxLines: 1),
          ),
            const Spacer(),
            UText.get(time, UIColor.color_t7, 12.rpx),
          ],
        ),
      ),
      onTap: () {
        // eventBus.fire(ClickCarPlateEvent(item.plateNo));
        // Navigator.of(context).pop();
        print(item.id);
        Api.getx(context, "/user/match_station?id=${item.id}",  progress: false, success: (res) {
          print(res);
          print(widget.station);
          print(res["station_name"]);
          // 站点大于20米或者收货站点为空直接带入
          if(widget.station == res["station_name"] || res["distance"]>20 || res["distance"]==0) {
            eventBus.fire(ClickCarPlateEvent(item.plateNo));
            Navigator.of(context).pop();
            return false;
          }
          CustomAlertDialog.showConfirmDialog(context,
              title: "根据场外车辆位置匹配的收货站点",
              content: "是否将收货站点  ${widget.station}  修改至  ${res["station_name"]}  ? ",
              confirmText: '确认修改', onConfirm: () {
                eventBus.fire(ClickAddressEvent(
                  res["lat"],
                  res["lng"],
                  res["station_alias_name"],
                  res["station_alias_id"] ==""?0:int.parse(res["station_alias_id"]),
                  res["station_name"],
                  res["station_id"],
                  // item.plateNo
                )
                );
                eventBus.fire(ClickCarPlateEvent(item.plateNo));

                Navigator.of(context).pop();
                // eventBus.fire(ClickCarPlateEvent(item.plateNo));
                // Navigator.of(context).pop();
              });

        }, failTip: "匹配站点失败", fail: (_) {

        });



      },
    );
  }

  sent(res,item) {
    eventBus.fire(ClickAddressEvent(
      res["lat"],
      res["lng"],
      res["station_alias_name"],
      res["station_alias_id"],
      res["station_name"],
      res["station_id"],
      // item.plateNo
    )
    );
    eventBus.fire(ClickCarPlateEvent(item.plateNo));
  }

  _onTextChange(String text) {
    if (text.isEmpty) {
      setState(() {
        _result.clear();
        _result.addAll(_data);
      });
    } else {
      _result.clear();

      print(_data.length);
      for (int i = 0; i < _data.length; i++) {
        var name = _data[i].plateNo;
        if (name.contains(text)) {
          _result.add(_data[i]);
        }
      }
      // print(_result);
      setState(() {

      });
    }

  }
}

